/**
* @program: src
*
* @description:
*
* @author: Mr.chen
*
* @create: 2020-11-11 14:37
**/
package models

import (
	"database/sql"
	//"ydd-im/service/api/tools/util"
	mydb "ydd-im/service/dbproxy/util/mysql/conn"
	//"errors"
	"fmt"
	"strings"
	"time"
)

const (
	SexWoman  = "W"
	SexMan    = "M"
	SexNukown = "U"
)

type User struct {
	Id          int       `db:"id" json:"id"`
	Username    string    `db:"username" json:"username"`
	Passwd      string    `db:"passwd" json:"-"`
	Avatar      string    `db:"avatar" json:"avatar"` //创建时间
	Sex         string    `db:"sex" json:"sex"`
	Nickname    string    `db:"nickname" json:"nickname"`
	Salt        string    `db:"salt" json:"-"`
	Online      int       `db:"online" json:"online"` //创建时间
	Memo        string    `db:"memo" json:"memo"`
	Createat    time.Time `db:"createat" json:"-"`
	Createatime string    `json:"createat"`
	Email       string    `db:"email" json:"email"`
	Sid         int       `db:"sid" json:"sid"`
	ClientId    string    `db:"clientId" json:"-"`
	UserKey     string    `db:"userkey" json:"-"`
	Token       string    `json:"token"`
}

//orm 回调
func (u *User) TableName() string {
	return TNUser()
}

func NewUser() *User {
	return &User{}
}
func (u *User) AddUser(user *User) (insertid int64, err error) {

	sqlStr := "insert  into " + u.TableName() + "(username, passwd,avatar,sex,nickname,salt,online,memo,createat,email,sid,userkey) values (?,?,?,?,?,?,?,?,?,?,?,?)"

	dbconn,err := mydb.DBConn("w")
	if err != nil {
		return 0, err
	}
	ret, err := dbconn.Exec(sqlStr, user.Username, user.Passwd, user.Avatar, user.Sex, user.Nickname, user.Salt, user.Online, user.Memo, user.Createat, user.Email, user.Sid, user.UserKey)

	if err != nil {
		return 0, err
	}
	theID, err := ret.LastInsertId() // 新插入数据的id
	if err != nil {
		return 0, err
	}
	return theID, nil
}

// 根据username,签名ID查询用户信息
func (u *User) GetUserInfo(username string, sid int) (user User, err error) {
	user = User{}
	signconfigure := &Signconfigure{}
	dbconn,err := mydb.DBConn("r")
	if err != nil {
		return user, err
	}
	if sid > 0 {
		sqlStr := "select a.id,a.username,a.passwd,a.avatar,a.sex,a.nickname,a.salt,a.online,a.memo,a.createat,a.email,a.sid,a.userkey from " + u.TableName() + " as a inner join " + signconfigure.TableName() + " as b on a.sid =b.id  where a.username=? and a.sid =?"

		err =dbconn.Get(&user, sqlStr, username, sid)
	} else {
		sqlStr := "select id,username, passwd,avatar,sex,nickname,salt,online,memo,createat,email,sid,userkey from " + u.TableName() + " where username=?"
		err = dbconn.Get(&user, sqlStr, username)
	}
	if err == sql.ErrNoRows { // 为空
		return user, nil
	}
	if err != nil {
		return user, err
	}
	return user, nil
}

// 根据签名ID查询所有用户列表
func (u *User) GetAllUserJoinSignList(sid, userid int) (user []User, err error) {
	user = []User{}
	signconfigure := &Signconfigure{}
	dbconn,err := mydb.DBConn("r")
	if err != nil {
		return user, err
	}
	if sid > 0 {
		sqlStr := "select a.id,a.username,a.passwd,a.avatar,a.sex,a.nickname,a.salt,a.online,a.memo,a.createat,a.email,a.sid from " + u.TableName() + " as a inner join " + signconfigure.TableName() + " as b on a.sid =b.id  where a.sid =? and a.id != ? order by a.id desc"
		err = dbconn.Select(&user, sqlStr, sid, userid)
	} else {
		sqlStr := "select id,username, passwd,avatar,sex,nickname,salt,online,memo,createat,email,sid from " + u.TableName() + " where id !=? order by id desc"
		err = dbconn.Select(&user, sqlStr, userid)
	}

	if err == sql.ErrNoRows { // 为空
		return user, nil
	}
	if err != nil {
		return user, err
	}
	return user, nil
}

/**
 * 获取用户记录
 * @access  public
 * @param   []string     where     条件
 * @param   string     field   获取的列
 * @param   int     pageNumber   第几页，从1开始
 * @param   int     pageCount   每页的数量
 * @param   string     orderby   排序
 * @return  []slice group   群列表
 * @return  error  err  错误信息
 */
func (u *User) GetUserList(where []string, field string, pageNumber, pageCount int, orderby string) (user []User, err error) {
	if len(field) == 0 {
		field = "id"
	}
	sqlStr := "select " + field + " from " + u.TableName() + " "
	if len(where) > 0 {
		whereStr := fmt.Sprintf(" WHERE %s", strings.Join(where, " AND "))

		//isok := util.FilteredSQLInject(whereStr)
		//fmt.Println(isok)
		//if (isok) {
		//	return user, errors.New("参数有误，请重试！")
		//}
		sqlStr += whereStr
	}
	if len(orderby) == 0 {
		sqlStr += " order by id asc"
	} else {
		sqlStr += " " + orderby
	}
	var firstlimit, endlimit int
	if pageCount > 0 {
		if pageNumber <= 1 {
			pageNumber = 1
		}
		firstlimit = (pageNumber - 1) * pageCount;;
		endlimit = pageCount;
		sqlStr += fmt.Sprintf(" limit %d,%d ", firstlimit, endlimit)
	} else {
		firstlimit = 0;
		endlimit = 0;
	}
	dbconn,err := mydb.DBConn("r")
	if err != nil {
		return user, err
	}
	fmt.Println(sqlStr)
	err = dbconn.Select(&user, sqlStr)
	if err == sql.ErrNoRows { // 为空
		return user, nil
	}
	if err != nil {
		return user, err
	}
	return user, nil
}
/**
 * 获取数组中的某一列
 * @param array arr 数组
 * @param string key_name  列名
 * @return array  返回那一列的数组
 */
func (u *User)  Get_arr_column(arr []User) (newArr []string,set map[string]bool) {
	newArr = make([]string, 0)
	set = make(map[string]bool,0)
	for k, _ := range arr {
		newArr = append(newArr, fmt.Sprintf("%d",arr[k].Id))
		set[fmt.Sprintf("%d",arr[k].Id)] = true
	}
	return newArr,set
}
